﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PhilipService;
using System.Threading.Tasks;
using PhilipService.Entity;
using TCommon;

namespace PhilipSupport.Controls.MainControl
{
    public partial class ServiceRecords : UserControl
    {
        public delegate void ViewDetailHandler(Control control);
        public event ViewDetailHandler ViewDetailClicked;
        private int PageSize = 20;
        private int VisibleSize = 5;
        private List<ServiceItem> items;
        private List<ServiceItem> origin_items;
        private DataTable table;

        public ServiceRecords()
        {
            InitializeComponent();
            pageControl.PageIndexChanged += PageControl_PageIndexChanged;
        }

        private void PageControl_PageIndexChanged(int pageIndex)
        {
            if (items == null)
                return;
            dataGridView.Columns.Clear();
            System.Data.DataTable dt = new DataTable("records");
            dt.Columns.Add(new DataColumn { ColumnName = "单位/医院" });
            dt.Columns.Add(new DataColumn { ColumnName = "姓名" });
            //dt.Columns.Add(new DataColumn { ColumnName = "手机" });
            dt.Columns.Add(new DataColumn { ColumnName = "服务开始时间" });
            //dt.Columns.Add(new DataColumn { ColumnName = "服务结束时间" });
            dt.Columns.Add(new DataColumn { ColumnName = "用户评价" });
            dt.Columns.Add(new DataColumn { ColumnName = "状态" });
            dt.Columns.Add(new DataColumn { ColumnName = "ID" });

            var startItemIndex = PageSize * (pageIndex-1);
            for (int i = 0; i < items.Count; i++)
            {
                
                if (i > startItemIndex-1 && i <= startItemIndex - 1 + PageSize)
                {
                    var item = items[i];
                    DataRow dr = dt.NewRow();
                    dr["单位/医院"] = item.CompanyName;
                    dr["姓名"] = item.Name;
                    //dr["手机"] = item.Phone;
                    dr["服务开始时间"] = item.StartTime;
                    //dr["服务结束时间"] = item.EndTime;
                    dr["用户评价"] = string.IsNullOrEmpty(item.Rating)? "": AppConst.UserRating[item.Rating];
                    dr["状态"] = item.IsClosed == 1 ? "已结单" : "未结单";
                    dr["ID"] = item.ServiceId;
                    dt.Rows.Add(dr);
                }
            }

            dataGridView.DataSource = dt;
            table = dt;
            dataGridView.Columns[5].Visible = false;
            DataGridViewButtonColumn col_view = new DataGridViewButtonColumn();
            col_view.Width = 100;
            col_view.FlatStyle = FlatStyle.Flat;
            col_view.DefaultCellStyle.ForeColor = Color.FromArgb(238, 245, 254);
            col_view.DefaultCellStyle.BackColor = Color.FromArgb(255, 39, 109, 158);
            col_view.HeaderText = "操作";
            col_view.Text = "查看";//加上这两个就能显示
            col_view.UseColumnTextForButtonValue = true;//
            dataGridView.Columns.Add(col_view);
        }

        public void DataSource(List<ServiceItem> items, bool isorigin = true) {
            if (items == null || items.Count == 0)
            {
                pageControl.Visible = false;
            }
            else
            {
                pageControl.Visible = true;
            }
            this.items = items;
            if (isorigin)
            {
                this.origin_items = items;
            }
            var totalPage = items.Count / PageSize + (items.Count % PageSize == 0 ? 0 : 1);
            pageControl.UpdatePageInfo(totalPage, 1, VisibleSize);
            dataGridView.Columns.Clear();
            System.Data.DataTable dt = new DataTable("records");
            dt.Columns.Add(new DataColumn { ColumnName = "单位/医院" });
            dt.Columns.Add(new DataColumn { ColumnName = "姓名" });
            //dt.Columns.Add(new DataColumn { ColumnName = "手机" });
            dt.Columns.Add(new DataColumn { ColumnName = "服务开始时间" });
            //dt.Columns.Add(new DataColumn { ColumnName = "服务结束时间" });
            dt.Columns.Add(new DataColumn { ColumnName = "用户评价" });
            dt.Columns.Add(new DataColumn { ColumnName = "状态" });
            dt.Columns.Add(new DataColumn { ColumnName = "ID" });

            for(int i = 0; i< items.Count; i++)
            {
                if (i < PageSize)
                {
                    var item = items[i];
                    DataRow dr = dt.NewRow();
                    dr["单位/医院"] = item.CompanyName;
                    dr["姓名"] = item.Name;
                    //dr["手机"] = item.Phone;
                    dr["服务开始时间"] = item.StartTime;
                    //dr["服务结束时间"] = item.EndTime;
                    dr["用户评价"] = string.IsNullOrEmpty(item.Rating) ? "" : AppConst.UserRating[item.Rating];
                    dr["状态"] = item.IsClosed == 1 ? "已结单" : "未结单";
                    dr["ID"] = item.ServiceId;
                    dt.Rows.Add(dr);
                }
            }

            dataGridView.DataSource = dt;
            table = dt;
            dataGridView.Columns[5].Visible = false;
            DataGridViewButtonColumn col_view = new DataGridViewButtonColumn();
            col_view.Width = 100;
            col_view.FlatStyle = FlatStyle.Flat;
            col_view.DefaultCellStyle.ForeColor = Color.FromArgb(238, 245, 254);
            col_view.DefaultCellStyle.BackColor = Color.FromArgb(255, 39, 109, 158);
            col_view.HeaderText = "操作";
            col_view.Text = "查看";//加上这两个就能显示
            col_view.UseColumnTextForButtonValue = true;//
            dataGridView.Columns.Add(col_view);
        }

        private void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {

        }

        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 6) {
                var id = long.Parse(this.dataGridView.Rows[e.RowIndex].Cells[5].Value.ToString());
                var status = this.dataGridView.Rows[e.RowIndex].Cells[4].Value.ToString();
                bool showButton = status == "已结单" ? false : true;
                var detail = new ServiceDetail(id, showButton);
                detail.ServiceClosed += Detail_ServiceClosed;
                Task.Factory.StartNew(() =>
                {
                    this.Invoke(new Action(() =>
                    {
                        ViewDetailClicked?.Invoke(detail);
                    }));
                });
                
            }
        }

        private void Detail_ServiceClosed(long serviceId)
        {
            if (table != null) {
                DataRow[] rows = table.Select("ID = " + serviceId);
                if (rows.Count() > 0) {
                    var row = rows[0];
                    row["状态"] = "已结单";
                }

                table.AcceptChanges();
            }
        }

        private void ServiceRecords_Load(object sender, EventArgs e)
        {
            tb_search.Setting(Color.FromArgb(255, 107, 107, 107));
            tb_search.Text = "";

            Task.Factory.StartNew(() =>
            {
                var manager = new RestServiceManager();
                var res = manager.GetServiceRecords(PhilipContext.UserId);
                var datasource = res.OrderByDescending(r => r.StartTime).ToList();
                this.Invoke(new Action(() =>
                {
                    DataSource(datasource);
                }));
            });
            
        }

        private void ServiceRecords_SizeChanged(object sender, EventArgs e)
        {
            var X = (this.Width - (panel_search.Width + btn_search.Width + 30)) / 2;
            panel_search.Location = new Point(X, panel_search.Location.Y);
            btn_search.Location = new Point(X + tb_search.Width + 30, btn_search.Location.Y);
        }

        private void btn_search_Click(object sender, EventArgs e)
        {
            if (this.origin_items.Count == 0)
                return;

            this.items = this.origin_items.Where(i => i.Name.Contains(tb_search.Text)).ToList();
            DataSource(items, false);
        }
    }
}
